import { ChatContext } from '@/app/chat-context';
import { apiInterceptors, getAppList, newDialogue, recommendApps, } from '@/client/api';
import { getRecommendQuestions } from '@/client/api/chat';
import TabContent from '@/new-components/app/TabContent';
import ChatInput from '@/new-components/chat/input/ChatInput';
import { STORAGE_INIT_MESSAGE_KET } from '@/utils';
import { useRequest } from 'ahooks';
import { ConfigProvider, Segmented, SegmentedProps, Tooltip } from 'antd';
import { t } from 'i18next';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useContext, useEffect, useState } from 'react';
import { Empty, } from 'antd';
import { onRouterChange } from '@/utils';
import { IApp } from '@/types/app';
import AppDefaultIcon from '../../common/AppDefaultIcon';
import MyEmpty from '@/components/common/MyEmpty';
const Active = 'recommend';
function ChatDefault() {
  const { setAgent: setAgentToChat, setCurrentDialogInfo, model, mode } = useContext(ChatContext);

  const router = useRouter();
  const [apps, setApps] = useState<any>({
    app_list: [],
    total_count: 0,
  });
  const [activeKey, setActiveKey] = useState(Active);
  const getAppListWithParams = (params: Record<string, string>) =>
    apiInterceptors(
      getAppList({
        ...params,
        page_no: '1',
        page_size: '6',
        ne_app_codes:["chat_with_db_metric_model_qa","chat_excel"]
      }),
    );
  const getHotAppList = (params: Record<string, string>) =>
    apiInterceptors(
      recommendApps({
        page_no: '1',
        page_size: '6',
        ...params,
        ne_app_codes:["chat_with_db_metric_model_qa","chat_excel"]
      }),
    );
  // 获取应用列表
  const {
    run: getAppListFn,
    loading,
    refresh,
  } = useRequest(
    async (app_name?: string) => {
      switch (activeKey) {
        case 'recommend':
          return await getHotAppList({});
        case 'used':
          return await getAppListWithParams({
            is_recent_used: 'true',
            need_owner_info: 'true',
            ...(app_name && { app_name }),
          });
        default:
          return [];
      }
    },
    {
      manual: true,
      onSuccess: res => {
        const [_error, data] = res;
        if (activeKey === 'recommend') {
          return setApps({
            app_list: data,
            total_count: data?.length || 0,
          });
        }
        setApps(data || {});
      },
      debounceWait: 500,
    },
  );
  useEffect(() => {
    getAppListFn();
  }, [activeKey, getAppListFn]);


  const items: SegmentedProps['options'] = [
    {
      value: 'recommend',
      label: t('recommend_apps'),
    },
    {
      value: 'used',
      label: t('used_apps'),
    },
  ];

  // 获取推荐问题
  const { data: helps } = useRequest(async () => {
    const [, res] = await apiInterceptors(getRecommendQuestions({ is_hot_question: 'true' }));
    return res ?? [];
  });

  const [hotQuestionsList, setHotQuestionsList] = useState([
    { title: '帮我搜索J35的飞行视频' },
    { title: '生成民航2023年运营情况' },
    { title: '帮我锁定孙一通的行动轨迹' },
    { title: '4月25号135登机口登机记录' },
    { title: '如何快速安装和引入组件？' },
  ] as any[]);
  const [searchList, setSearchList] = useState([] as any[]);
  const filterAry = ['chat_normal', 'chat_with_db_qa']
  useEffect(() => {
    if (activeKey === Active) {
      const usedData = (apps?.app_list || [])
        // .filter((item: any) => {
        //   return !filterAry.includes(item.app_code)
        // })
        .map((item: any) => {
          return {
            ...item,
            // app_name: item.app_code == 'chat_excel' ? 'Excel对话'
            //   : item.app_code == 'chat_dashboard' ? '仪表板生成'
            //     : item.app_code == 'chat_with_db_execute' ? '智能数据分析'
            //       : item.app_code == 'chat_knowledge' ? '知识库分析' : item.app_name,
            icon: <AppDefaultIcon scene={item?.team_context?.chat_scene || 'chat_agent'} />,
          }
        })
      setSearchList(usedData);
    }
  }, [activeKey, apps])

  const toChat = async (data: IApp) => {
    // 原生应用跳转
    if (data.team_mode === 'native_app') {
      const { chat_scene = '' } = data.team_context;
      const [, res] = await apiInterceptors(newDialogue({ chat_mode: chat_scene }));
      if (res) {
        setCurrentDialogInfo?.({
          chat_scene: res.chat_mode,
          app_code: data.app_code,
        });
        localStorage.setItem(
          'cur_dialog_info',
          JSON.stringify({
            chat_scene: res.chat_mode,
            app_code: data.app_code,
          }),
        );
        router.push(`/chat?scene=${chat_scene}&id=${res.conv_uid}${model ? `&model=${model}` : ''}`);
      }
    } else {
      // 自定义应用
      const [, res] = await apiInterceptors(newDialogue({ chat_mode: 'chat_agent' }));
      if (res) {
        setCurrentDialogInfo?.({
          chat_scene: res.chat_mode,
          app_code: data.app_code,
        });
        localStorage.setItem(
          'cur_dialog_info',
          JSON.stringify({
            chat_scene: res.chat_mode,
            app_code: data.app_code,
          }),
        );
        setAgentToChat?.(data.app_code);
        router.push(`/chat/?scene=chat_agent&id=${res.conv_uid}${model ? `&model=${model}` : ''}`);
      }
    }
  };
  const talkClick = async (userInput: string) => {
    if (!userInput.trim()) {
      return;
    };

    const [, res] = await apiInterceptors(newDialogue({ chat_mode: 'chat_normal' }));
    if (res) {
      setCurrentDialogInfo?.({
        chat_scene: res.chat_mode,
        app_code: res.chat_mode,
      });
      localStorage.setItem(
        'cur_dialog_info',
        JSON.stringify({
          chat_scene: res.chat_mode,
          app_code: res.chat_mode,
        }),
      );
      localStorage.setItem(STORAGE_INIT_MESSAGE_KET, JSON.stringify({ id: res.conv_uid, message: userInput }));
      router.push(`/chat/?scene=chat_normal&id=${res.conv_uid}`);
    }
  };
  const renderTitle = (data: { title: string, desc: string }) => {
    return (
      <div className='flex flex-col gap-2'>
        <div className='text-lg weight-400'>{data.title}</div>
        <div className='text-sm weight-400 opacity-70'>{data.desc}</div>
      </div>
    )
  }

  const routerImg = () => {
    return <>
      {
        mode === 'dark' ? <Image
          className='ml-3 bg-cover bg-repeat'
          src='/ai/router-dark.png'
          alt=""
          width={25}
          height={25}
        />
          : <Image
            className='ml-3'
            src='/ai/router.png'
            alt=""
            width={6}
            height={6}
          />
      }
    </>
  }
  return (
    <ConfigProvider
      theme={{
        components: {
          Button: {
            defaultBorderColor: 'white',
          },
          Segmented: {
            itemSelectedBg: '#8665FF',
            itemSelectedColor: 'white',
          },
        },
      }}
    >
      <div className={`px-28 py-10 h-full flex flex-col justify-between bg-cover bg-repeat ${mode === 'dark' ? 'bg-welcome-bg-dark' : 'bg-welcome-bg'}`}>
        <div className='flex justify-center items-center w-full h-full flex-col gap-3'>
          <div className='flex items-center mb-2 text-base'>
            <Image
              src="/ai/ai-animation.gif"
              alt="login"
              width={150}
              height={150}
              className='mr-3'
            />
            <div className='flex flex-col gap-3'>
              { mode === 'dark' ? <Image
                src="/ai/welcome-dark.png"
                alt="login"
                width={400}
                height={60}
              /> :
              <Image
                src="/ai/welcome.png"
                alt="login"
                width={400}
                height={60}
              /> }
              <div>{t('create_dialogue_desc')}</div>
            </div>
          </div>
          <div className='flex items-center justify-center gap-3 w-full'>
            <div className={`flex flex-col gap-3 rounded-lg ${mode === 'dark' ? 'bg-welcome-t1-dark' : 'bg-welcome-t1'} bg-cover bg-center bg-repeat p-4 w-80 h-96`}>
              {renderTitle({ title: t('welcome1'), desc: t('welcome1_desc') })}
              <div className='overflow-y-auto h-72 text-base'>
                {
                  hotQuestionsList?.length ?
                    hotQuestionsList.map((item, index) => {
                      return (
                        <div onClick={() => talkClick(item.title)} className={`px-2 py-1 hover:bg-slate-200 dark:hover:bg-theme-dark rounded cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis ${index == 0 ? 'mt-1' : 'mt-2'}`} >
                          <span className={index == 0 ? 'text-T1' : index == 1 ? 'text-T2' : index == 2 ? 'text-T3' : ''}>{index + 1} </span>{item.title}
                        </div>
                      )
                    })
                    :
                    <MyEmpty description='无数据' />
                }
              </div>
            </div>
            <div className={`flex flex-col gap-3 rounded-lg ${mode === 'dark' ? 'bg-welcome-t2-dark' : 'bg-welcome-t2'} bg-cover bg-center bg-repeat p-4 w-80 h-96`}>
              {renderTitle({ title: t('welcome2'), desc: t('welcome2_desc') })}
              <div className='overflow-y-auto h-72 text-base'>
                {
                  searchList?.length ?
                    searchList.map((item, index) => {
                      return (
                        <div
                          onClick={() => toChat(item)} className={`cursor-pointer flex items-center gap-2 w-full h-10 px-4 bg-[#fff] dark:bg-theme-dark rounded-xl ${searchList.length == index ? '' : 'mt-2'}`} >
                          {/* <Image
                            src={item.icon}
                            alt=""
                            width={30}
                            height={30}
                          /> */}

                          <Tooltip title={item.app_code}>
                            <div className='flex items-center justify-center w-8 h-8 rounded-lg mr-3 bg-white'>{item.icon}</div>
                          </Tooltip>
                          <div>{item.app_name}</div>
                        </div>
                      )
                    })
                    :
                    <MyEmpty description='无数据' />
                }
              </div>
            </div>
            <div className='flex flex-col gap-3 w-80 h-96'>
              <div className={`flex flex-col gap-3 rounded-lg ${mode === 'dark' ? 'bg-welcome-t3-dark' : 'bg-welcome-t3'} bg-cover bg-center bg-repeat p-4 w-full h-1/2`}>
                {renderTitle({ title: t('welcome3'), desc: t('welcome3_desc') })}
                <div
                  onClick={() => {
                    router.push('/construct/app');
                  }}
                  className={`mt-10 cursor-pointer flex items-center justify-center gap-2 w-full h-10 px-4 bg-[#fff] dark:bg-theme-dark rounded-3xl`} >
                  <Image
                    src={`${mode === 'dark' ? '/ai/s5-dark.png' : '/ai/s5.png'}`}
                    className='bg-cover bg-repeat'
                    alt=""
                    width={15}
                    height={15}
                  />
                  <div>{t('welcome3_router')}</div>
                  {routerImg()}
                </div>
              </div>
              <div className={`flex flex-col gap-3 rounded-lg ${mode === 'dark' ? 'bg-welcome-t4-dark' : 'bg-welcome-t4'} bg-cover bg-center bg-repeat p-4 w-full h-1/2`}>
                {renderTitle({ title: t('welcome4'), desc: t('welcome4_desc') })}
                <div onClick={() => {
                  router.push('/construct/knowledge');
                }}
                  className={`mt-8 cursor-pointer flex items-center gap-2 w-40 h-10 px-4 bg-[#fff] dark:bg-theme-dark rounded-3xl`} >
                  <div className='ml-2'>{t('welcome4_router')}</div>
                  {routerImg()}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <ChatInput />
        </div>
      </div>
    </ConfigProvider>
  );
}

export default ChatDefault;
